package com.itbaizhan.shopping_pay_service.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.itbaizhan.shopping_common.exception.BusException;
import com.itbaizhan.shopping_common.pojo.Orders;
import com.itbaizhan.shopping_common.pojo.Payment;
import com.itbaizhan.shopping_common.result.CodeEnum;
import com.itbaizhan.shopping_common.service.ZfbPayService;
import com.itbaizhan.shopping_pay_service.config.ZfbPayConfig;
import com.itbaizhan.shopping_pay_service.mapper.PaymentMapper;
import com.itbaizhan.shopping_pay_service.util.ZfbVerifierUtil;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @author spf
 * @date 2024/1/19
 * @time 20:51
 */

// 支付服务实现类
@Service
@Component
@Transactional
public class ZfbPayServiceImpl implements ZfbPayService {

    @Autowired
    private PaymentMapper paymentMapper;
    @Autowired
    private ZfbPayConfig zfbPayConfig;
    @Autowired
    private AlipayClient alipayClient;

    @Override
    public String pcPay(Orders orders) {
        // 创建请求
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        // 设置请求内容
        request.setNotifyUrl(zfbPayConfig.getNotifyUrl() + zfbPayConfig.getPcNotify());
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orders.getId()); // 订单编号
        bizContent.put("total_amount", orders.getPayment()); // 订单金额
        bizContent.put("subject", orders.getCartGoods().get(0).getGoodsName()); // 订单标题
        request.setBizContent(bizContent.toString());
        try {
            // 发送请求,获取响应
            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            return response.getQrCode();
        } catch (AlipayApiException e) {
            throw new BusException(CodeEnum.QR_CODE_ERROR);
        }
    }

    @Override
    public void checkSign(Map<String, Object> paramMap) {
        Map<String, String[]> requestParameterMap = (Map<String, String[]>) paramMap.get("requestParameterMap");
        boolean valid = ZfbVerifierUtil.isValid(requestParameterMap, zfbPayConfig.getPublicKey());
        if (!valid){
            throw new BusException(CodeEnum.CHECK_SIGN_ERROR);
        }
    }

    @Override
    public void addPayment(Payment payment) {
        paymentMapper.insert(payment);
    }
}
